package de.wiroo.setup.web.common;

import java.util.HashMap;
import java.util.Map;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.event.Broadcast;
import org.apache.wicket.markup.html.form.Form;

public abstract class ActionButton<R, P> extends IconButton {
	protected static final Map<String, String> ACTION_TO_BTN_KIND = new HashMap<String, String>();

	static {
		ACTION_TO_BTN_KIND.put(IServiceBindings.ACTION_ID_DELETE, IconButton.DELETE);
		ACTION_TO_BTN_KIND.put(IServiceBindings.ACTION_ID_UPDATE, IconButton.EDIT);		
		ACTION_TO_BTN_KIND.put(IServiceBindings.ACTION_ID_SAVE, IconButton.SAVE);
		ACTION_TO_BTN_KIND.put(IServiceBindings.ACTION_ID_CREATE, IconButton.NEW);
	}
	

	ActionButton(String id, Form<?> form) {
		super(id, form);
	}

	@Override
	protected void onError(AjaxRequestTarget target, Form<?> form) {
		if(target!=null){
			target.add(form);
		}
	}

	@Override
	protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
		//TODO: Actions with confirmation... (How confirmation is done must be decided by the page?)
		P param = getParamForAction();
		R result = getAction().execute(param);

		//TODO: Is this the proper broadcast type?
	    send(this.getPage(), Broadcast.BREADTH, new ActionEvent<R,P>(getAction(), param, result, target));
	}

	@Override
	protected String getKind() {
		return getButtonKindForAction(getAction());
	}
	
	protected abstract IAction<R, P> getAction() ;
	

	protected String getButtonKindForAction(final IAction<?,?> action) {
		return ACTION_TO_BTN_KIND.get(action.getActionId());
	}
	
	protected abstract P getParamForAction();
	
	
}